<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" @close="closeDialog" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="120px" class="demo-ruleForm">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="登录账号" prop="username">
							<el-input v-model="state.ruleForm.username" placeholder="请输入账户名称" clearable></el-input>
						</el-form-item>
                        <el-form-item label="管理员昵称" prop="nickname">
                            <el-input v-model="state.ruleForm.nickname" placeholder="请输入管理员昵称" clearable></el-input>
                        </el-form-item>
						<el-form-item label="">
							<el-alert
								v-if="state.dialog.type == 'add'"
								title="初始化密码：登录账号"
								type="error"
								:closable="false"
							></el-alert>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管理员头像" prop="avatar">
                            <el-upload
                                v-model="state.ruleForm.avatar"
                                class="avatar-uploader"
                                :action="BASE_URL + 'lxs/upload/upload_file'"
                                :data="{name: 'avatar'}"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="handleCoverSuccess"
                            >
                                <img v-if="state.ruleForm.avatar" :src="state.ruleForm.avatar" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="角色" prop="role_id">
                            <el-select v-model="state.ruleForm.role_id" placeholder="请选择角色">
                                <el-option
                                    v-for="item in roleList"
                                    :key="item.id"
                                    :label="item.role_name"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-show="false">
						<el-form-item label="管理员状态">
							<el-switch v-model="state.ruleForm.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用"></el-switch>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import {nextTick, reactive, ref} from 'vue';
import {ElMessage, type UploadProps} from 'element-plus'
import {BASE_URL} from "/@/utils/config";
import {Plus} from "@element-plus/icons-vue";
import {useUserApi} from "/@/api/permission/user";


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const ruleFormRef = ref(null);
const state = reactive({
	ruleForm: {
		username: '', // 账户名称
        nickname: '', // 管理员昵称
        avatar: '',
        role_id: '',
		status: 1, // 管理员状态
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 图片尺寸限制
const beforeUpload = (file: any) => {
	const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt500KB = file.size / 1024 / 1024 > 2;

	if (!isJPGorPNG) {
		ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
		return false;
	}
	if (isLt500KB) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		return false;
	}
	console.log('isJPGorPNG && isLt500KB', isJPGorPNG && isLt500KB)
}

const handleCoverSuccess: UploadProps['onSuccess'] = (
    response
) => {
    state.ruleForm.avatar = response.data.url
}

const rules = reactive ({
    username: [
        { required: true, message: '请填写管理员账号', trigger: 'blur' },
    ],
	avatar: [
        { required: true, message: '请上传管理员头像', trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '请填写管理员昵称', trigger: 'blur' },
    ],
    role_id: [
        { required: true, message: '请选择角色', trigger: 'blur' },
    ],
})

// 打开弹窗
const openDialog = (type, row) => {
	if (type === 'edit') {
		state.ruleForm = row;
		state.dialog.title = '修改管理员';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '新增管理员';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		nextTick(() => {
            ruleFormRef.value.resetFields();
		});
	}
	state.dialog.isShowDialog = true;
    state.dialog.type = type;
};

defineProps(['roleList']);


// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
	ruleFormRef.value.resetFields();
    emit('refresh');
};

// 提交
const onSubmit = () => {
	ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            useUserApi().adminFormSubmit(state.ruleForm).then((res) => {
                if (res.code == 200) {
                    ElMessage.success(res.message);
                } else {
                    ElMessage.error(res.message);
                }
	            closeDialog();
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped>
.el-alert {
	padding: 0;
}
.el-alert:first-child {
	margin: 0;
}
</style>
<style>
.avatar-uploader .avatar {
    width: 148px;
    height: 148px;
    display: block;
}
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    text-align: center;
}
</style>
<style lang="scss">
.custom-header {
    .el-checkbox {
        display: flex;
        height: unset;
    }
}
</style>
